<!--
 * @Author: zhuhaohua 250293786@qq.com
 * @Date: 2024-01-02 10:21:51
 * @LastEditors: zhayang 1063975710@qq.com
 * @LastEditTime: 2024-07-03 21:38:32
 * @FilePath: \heart-backed\src\views\banner\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container fit overflow-auto flex flex-col">
    <div class="info-bar m-b-20 col-auto">
      <div class="info-card rd-8 bg-#fff flex top-head-box">
        <div class="info-img col-auto m-r-20 center">
          <img
            class="w-100 h-100"
            src="@/assets/images/subscribe/zcl.png"
          />
        </div>
        <div class="info-content col flex flex-col full-h justify-center">
          <div class="info-title text-14 c-#6A6B6C">总处理预约数</div>
          <div
            class="info-bottom ellipsis m-t-8 text-24 font-600 c-#1C1F23 flex items-baseline"
          >
            {{ dispose_finish }}
            <div class="text-16 font-600">条</div>
          </div>
          <div class="info-foot">
            <div class="flex">
              <div class="txt">预约管理</div>
              <div
                class="tag"
                @click="dialogShowVisible = true"
              >
                {{
                  schema_type === '未选择' ? '未选择' : `已选：${schema_type}`
                }}
              </div>
            </div>
            <div
              class="setting"
              @click="goto('/common-function/subscribe-setting')"
            >
              去设置
              <i class="el-icon-arrow-right"></i>
            </div>
          </div>
        </div>
      </div>

      <InfoCard
        v-for="(item, index) in infoData"
        :key="index"
        :data="item"
      />
    </div>

    <ContainerCard
      title="预约记录"
      class="col"
    >
      <template #title-right>
        <el-radio-group
          v-model="dateTime"
          size="small"
          style="margin-right: 10px"
        >
          <el-radio-button label="1">1天</el-radio-button>
          <el-radio-button label="3">3天</el-radio-button>
          <el-radio-button label="7">1周</el-radio-button>
          <el-radio-button label="30">1个月</el-radio-button>
        </el-radio-group>
        <DateRangePicker2
          v-model="timeArr"
          class="w-240 flex"
        />
      </template>
      <div class="chart-item bg-#fff h-300 full-w">
        <div
          ref="myChart"
          style="width: 100%; height: 100%"
        ></div>
        <!-- <LineChart
          :echarts-data="echartsData"
          ref="chartRef"
        /> -->
      </div>
      <div class="table-area full-w m-t-20">
        <div class="full-w h-300">
          <BaseTable
            :columns="column"
            :table-data="tableData"
          >
            <template #icon="{ row }">
              <div class="flex itemAlign-center">
                <img
                  :src="row.users_info_payload.apply_user_info.icon"
                  alt=""
                  class="head"
                />
              </div>
            </template>
            <template #scheduled_date="{ row }">
              <div class="flex itemAlign-center">
                {{ row.scheduled_date }} {{ row.start_time_frame }}-{{
                  row.end_time_frame
                }}
              </div>
            </template>
            <template #action="{ row }">
              <el-button
                type="text"
                size="small"
                @click="agree(row)"
              >
                同意
              </el-button>
              <el-button
                type="text"
                size="small"
                class="c-#ff2727!important"
                @click="cancel(row)"
              >
                拒绝
              </el-button>
            </template>
          </BaseTable>
        </div>

        <Pagination
          class="m-t-20"
          :pagination-data="pageData"
        />
      </div>
    </ContainerCard>

    <el-dialog
      title="选择预约展示方式"
      :visible.sync="dialogShowVisible"
      width="800"
    >
      <div class="flex justify-around">
        <div
          :class="['item-show', showType == 1 ? 'on' : '']"
          @click="selectType(1)"
        >
          <img
            src="@/assets/images/subscribe/type1.png"
            alt=""
            class="w-80 h-80"
          />
          <div>跳转链接</div>
          <img
            src="@/assets/images/subscribe/check.png"
            alt=""
            class="check"
          />
        </div>
        <div
          :class="['item-show', showType == 2 ? 'on' : '']"
          @click="selectType(2)"
        >
          <img
            src="@/assets/images/subscribe/type2.png"
            alt=""
            class="w-80 h-80"
          />
          <div>图片说明展示</div>
          <img
            src="@/assets/images/subscribe/check.png"
            alt=""
            class="check"
          />
        </div>
        <div
          :class="['item-show', showType == 3 ? 'on' : '']"
          style="margin-right: 0"
          @click="selectType(3)"
        >
          <img
            src="@/assets/images/subscribe/type1.png"
            alt=""
            class="w-80 h-80"
          />
          <div>平台预约</div>
          <img
            src="@/assets/images/subscribe/check.png"
            alt=""
            class="check"
          />
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogShowVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="showSave"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="预约管理 - 跳转链接"
      :visible.sync="linkShowVisible"
      width="800"
    >
      <div class="">
        <div class="addr">链接地址</div>
        <el-input
          v-model="addr"
          placeholder="请输入内容"
        />
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="linkShowVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="linkSave"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="预约管理 - 图片说明展示"
      :visible.sync="picShowVisible"
      width="800"
    >
      <div class="">
        <up-image-sub
          :list="imgList"
          @imgList="getImgList"
          @del="delImg"
          @push="pushImg"
          @progress="changeProgress"
        />
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="picShowVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="picSave"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import InfoCard from '@/components/bmp/card/info-card-subscribe.vue'
import ContainerCard from '@/components/bmp/card/container-card.vue'
import { DateRangePicker2 } from '@/components/bmp/form/index'
import {
  getSchema,
  saveSchema,
  getCollect,
  getChartReport
} from '@/api/subscribe'
import { listSubscribe, cancelSubscribe } from '@/api/my-subscribe'
import BaseTable from '@/components/bmp/table/index.vue'
import Pagination from '@/components/pagination/pagination'
import upImageSub from '@/components/upload/up-image-sub.vue'
export default {
  components: {
    InfoCard,
    ContainerCard,
    DateRangePicker2,
    BaseTable,
    Pagination,
    upImageSub
  },
  data() {
    return {
      infoData: [
        {
          label: '被约未处理总数',
          value: '10',
          unit: '人',
          img: require('@/assets/images/subscribe/wcl.png')
        },
        {
          label: '未来一周预约数',
          value: '122',
          unit: '人',
          img: require('@/assets/images/subscribe/wlyy.png')
        },
        {
          label: '未来3日内预约数',
          value: '122',
          unit: '人',
          img: require('@/assets/images/subscribe/threeyy.png')
        }
      ],
      dateTime: '30',
      dialogShowVisible: false,
      echartsData: {
        title: {
          show: false,
          name: 'title'
        },
        legend: {
          show: false,
          data: []
        },
        xAxis: {
          name: ''
          // data: ['1', '2', '3', '4']
        },
        yAxis: [{ name: '', unit: '' }],
        colorList: ['#00AAFF', '#00FFFF', '#00AAFF', '#00AAFF'],
        series: [
          // [
          //   { name: '一级报警', value: 53 },
          //   { name: '一级报警', value: 35 },
          //   { name: '一级报警', value: 25 }
          // ],
          // [
          //   { name: '二级报警', value: 100 },
          //   { name: '二级报警', value: 200 },
          //   { name: '二级报警', value: 300 }
          // ]
        ]
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      column: [
        {
          prop: 'icon',
          label: '头像'
        },
        {
          prop: 'contact_name',
          label: '姓名'
        },
        {
          prop: 'contact_phone',
          label: '联系电话'
        },
        {
          prop: 'scheduled_date',
          label: '预约时间'
        },
        {
          prop: 'action',
          label: '操作'
        }
      ],
      tableData: [],
      pageData: {
        currentPage: 1,
        pageSize: 9,
        total: 0
      },
      schema_type: '未选择',
      dispose_finish: 0,
      showType: 1,
      linkShowVisible: false,
      addr: '',
      picShowVisible: false,
      imgList: [],
      startTime: '',
      endTime: '',
      timeArr: []
    }
  },
  watch: {
    timeArr: {
      handler(val) {
        if (val && val.length === 2) {
          this.dateTime = null
          this.startTime = val[0]
          this.endTime = val[1]
          this.getEchart()
        } else {
          // this.dateTime = '30'
        }
      },
      deep: true
    },
    dateTime: {
      handler(val) {
        if (!val || val === '0') {
          this.startTime = undefined
          this.endTime = undefined
        } else {
          // this.$set(this, 'timeArr', [])
          this.startTime = this.getDateTime(new Date())
          this.endTime = this.getDateTime(new Date(), val)
          this.timeArr = []
          this.getEchart()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {},
  mounted() {
    this.$nextTick(() => {
      this.init()
    })
    // 窗口监听变化
    window.addEventListener('resize', this.resize)
    this.getInfo()
    this.getSchemaConfig()
    this.getSubscribeList()
    this.getEchart()
  },
  beforeDestroy() {
    if (!!this._chart && this._chart !== null) {
      this._chart.dispose() // 销毁echarts实例
      window.removeEventListener('resize', this.resize) // 移除尺寸变化事件
      this._chart = null
    }
  },
  methods: {
    agree(row) {
      const that = this
      this.$confirm('确认同意预约?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = {
            reservation_id: row.id,
            dispose_switch: 1
          }
          cancelSubscribe(data).then((res) => {
            that.$message.success('操作成功')
            that.getSubscribeList()
          })
        })
        .catch(() => {
          //
        })
    },
    cancel(row) {
      const that = this
      this.$confirm('确认拒绝预约?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const data = {
            reservation_id: row.id,
            dispose_switch: 2
          }
          cancelSubscribe(data).then((res) => {
            that.$message.success('操作成功')
            that.getSubscribeList()
          })
        })
        .catch(() => {
          //
        })
    },
    init() {
      this._chart = this.$echarts.init(this.$refs.myChart)
      const option = {
        title: {
          show: this.echartsData.title.show,
          text: this.echartsData.title.name,
          textStyle: {
            fontSize: 16,
            fontFamily: 'PingFang SC',
            fontWeight: 500,
            color: '#F4BB76'
          },
          left: 'center',
          top: 0
        },
        legend: {
          show: !!this.echartsData?.legend?.show,
          type: 'plain',
          left: 'right',
          top: 5,
          itemWidth: 12,
          itemHeight: 7,
          textStyle: {
            fontSize: 12,
            color: '#fff'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: this.grid,
        xAxis: [
          {
            name: this.echartsData.xAxis.name,
            nameTextStyle: {
              color: '#fff',
              fontSize: '10px',
              padding: [0, 0]
            },
            boundaryGap: true,
            type: 'category',
            data: this.echartsData.xAxis.data,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              color: '#333'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#e0e0e0'
              }
            }
          }
        ],
        yAxis: [],
        series: []
      }
      option.yAxis = []
      for (let i = 0; i < this.echartsData.yAxis.length; i++) {
        const yData = this.echartsData.yAxis[i]
        option.yAxis.push({
          name: yData.name + yData.unit,
          nameLocation: 'end',
          nameTextStyle: {
            color: 'rgba(110, 206, 254, 1)',
            fontSize: '13px'
          },
          type: 'value',
          axisLine: {
            show: false,
            lineStyle: {
              color: '#e0e0e0'
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: '#e0e0e0',
              type: 'dashed'
            }
          },
          axisLabel: {
            color: '#000',
            formatter: '{value}'
          }
        })
      }
      option.series = []
      for (let i = 0; i < this.echartsData.series.length; i++) {
        const serData = this.echartsData.series[i]
        option.series.push({
          name: this.echartsData.legend.data[i],
          type: 'line',
          symbol: 'none',
          smooth: true, // 让折线变得顺滑
          itemStyle: {
            color: this.echartsData.colorList[i]
          },
          emphasis: {
            focus: 'series'
          },

          animationDelay: function (idx) {
            return idx * 50
          },
          yAxisIndex: 0,
          data: serData
        })
        if (this.lineArea[i]) {
          option.series[i].areaStyle = {
            show: false,
            color: this.echartsData.colorList[i],
            opacity: 0.1
          }
        }
      }
      // 清除之前图形
      this._chart.clear()
      this._chart.setOption(option)
    },
    resize() {
      setTimeout(() => {
        this._chart.resize()
      }, 500)
    },
    dateRangeArray(startDate, endDate) {
      let dates = []
      let currentDate = new Date(startDate)
      while (currentDate <= endDate) {
        let y = new Date(currentDate).getFullYear()
        let m = (new Date(currentDate).getMonth() + 1)
          .toString()
          .padStart(2, '0')
        let d = new Date(currentDate).getDate().toString().padStart(2, '0')
        dates.push(`${y}${m}${d}`)
        currentDate.setDate(currentDate.getDate() + 1)
      }
      return dates
    },
    // 折线图
    getEchart() {
      getChartReport({
        start_date: this.startTime,
        end_date: this.endTime
      }).then((res) => {
        let xData = this.dateRangeArray(
          new Date(this.startTime),
          new Date(this.endTime)
        )
        // const _arr = []
        // _arr[0] = {}
        // _arr[0].data = res.data.all.map((v) => {
        //   return [v.scheduled_date, v.qty]
        // })
        let arr = []
        arr[0] = xData.map((v) => {
          let _obj = res.data.all.find((x) => {
            return x.scheduled_date == v
          })
          if (_obj) {
            return [v, _obj.qty]
          } else {
            return [v]
          }
        })
        arr[1] = xData.map((v) => {
          let _obj = res.data.dispose_finish.find((x) => {
            return x.scheduled_date == v
          })
          if (_obj) {
            return [v, _obj.qty]
          } else {
            return [v]
          }
        })
        arr[2] = xData.map((v) => {
          let _obj = res.data.dispose_wait.find((x) => {
            return x.scheduled_date == v
          })
          if (_obj) {
            return [v, _obj.qty]
          } else {
            return [v]
          }
        })

        // 图表问题
        this.echartsData = {
          title: {
            show: false,
            name: 'title'
          },
          legend: {
            show: false,
            data: []
          },
          xAxis: {
            name: '',
            data: xData
          },
          yAxis: [{ name: '', unit: '' }],
          colorList: ['#04D1B8', '#F5B763', '#2893FF'],
          series: arr
        }
        this._chart && this._chart.setOption(this.echartsData)
      })
    },
    getDateTime(date, type) {
      if (type && type !== '30') {
        date.setDate(date.getDate() + (type - 1))
      } else if (type && type === '30') {
        date.setMonth(date.getMonth() + 1)
      }
      const today = date
      const year = today.getFullYear()
      const month = today.getMonth() + 1 // getMonth() 返回的月份是从 0 开始的
      const day = today.getDate()
      // 输出格式为 YYYY-MM-DD
      return `${year}-${month.toString().padStart(2, '0')}-${day
        .toString()
        .padStart(2, '0')}`
    },
    getSubscribeList() {
      listSubscribe({
        dispose_switch: 0,
        type: 1
      }).then((res) => {
        this.tableData = res.data.data
        this.pageData.total = res.data.total
      })
    },
    changeProgress(len, num) {
      this.$set(this.imgList[len], 'progress', num)
    },
    delImg(i) {
      this.imgList.splice(i, 1)
    },
    pushImg(obj) {
      this.imgList.push(obj)
    },
    picSave() {
      saveSchema({
        schema_type: 1,
        payload: {
          image_url: this.imgList.map((v) => v.url).join(',')
        }
      }).then((res) => {
        this.$message.success('设置成功')
        this.schema_type = '图片说明'
        this.picShowVisible = false
      })
    },
    linkSave() {
      saveSchema({
        schema_type: 2,
        payload: {
          link_url: this.addr
        }
      }).then((res) => {
        this.$message.success('设置成功')
        this.schema_type = '跳转链接'
        this.linkShowVisible = false
      })
    },
    getInfo() {
      getCollect().then((res) => {
        this.$set(this.infoData[0], 'value', res.data.dispose_wait)
        this.$set(this.infoData[1], 'value', res.data.wait_7)
        this.$set(this.infoData[2], 'value', res.data.wait_3)
        this.dispose_finish = res.data.dispose_finish
      })
    },
    getSchemaConfig() {
      getSchema().then((res) => {
        if (res.data.schema_type === 0) {
          this.schema_type = '平台预约'
        } else if (res.data.schema_type === 1) {
          this.schema_type = '图片说明展示'
        } else if (res.data.schema_type === 2) {
          this.schema_type = '跳转链接'
        } else {
          this.schema_type = '未选择'
        }
      })
    },
    selectType(type) {
      this.showType = type
    },
    getImgList(len, src) {
      this.$set(this.imgList[len], 'url', src)
    },
    showSave() {
      if (this.showType === 3) {
        // 站内
        saveSchema({ schema_type: 0 }).then((res) => {
          this.$message.success('设置成功')
          this.schema_type = '平台预约'
          this.dialogShowVisible = false
        })
      } else if (this.showType === 1) {
        this.addr = undefined
        this.linkShowVisible = true
        this.dialogShowVisible = false
      } else if (this.showType === 2) {
        this.imgList = []
        this.dialogShowVisible = false
        this.picShowVisible = true
      }
    },
    goto(url) {
      this.$router.push({ path: url, query: {} })
    }
  }
}
</script>
<style lang="scss" scoped>
.info-bar {
  display: flex;
  // grid-template-columns: repeat(3, 1fr);
  // gap: 20px;
}
.charts-area {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.info-card {
  height: 145px;
  position: relative;
  padding: 20px;
  margin-right: 20px;
  &:last-child {
    margin-right: 0;
  }
}
.top-head-box {
  background: linear-gradient(270deg, #e9fbf7 0%, #ffffff 60%);
  border-radius: 8px 8px 8px 8px;
  border: 1px solid;
  border-image: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0)
    )
    1 1;
  width: 100%;
  .info-title {
    font-weight: 500;
    font-size: 16px;
    color: #1c1f23;
  }
  .info-content {
    .info-bottom {
      padding-bottom: 12px;
      border-bottom: 1px solid #e0e0e0;
    }
    .info-foot {
      margin-top: 14px;
      font-weight: 400;
      font-size: 14px;
      color: #1c1f23;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .txt {
        font-weight: 400;
        font-size: 14px;
        color: #1c1f23;
      }
      .tag {
        cursor: pointer;
        background: linear-gradient(
          90deg,
          rgba(57, 217, 198, 0.2) 0%,
          rgba(57, 207, 162, 0.2) 100%
        );
        border-radius: 2px;
        font-weight: 400;
        font-size: 10px;
        color: #04d1b8;
        line-height: 12px;
        text-align: center;
        font-style: normal;
        text-transform: none;
        padding: 2px 8px;
        margin-left: 4px;
      }
      .setting {
        background: linear-gradient(90deg, #39d9c6 0%, #39cfa2 100%);
        border-radius: 4px;
        color: #fff;
        padding: 2px 8px;
        font-size: 12px;
        cursor: pointer;
      }
    }
  }
}
.item-show {
  font-weight: 500;
  font-size: 16px;
  color: #1c1f23;
  display: flex;
  justify-content: start;
  align-items: center;
  padding: 20px;
  margin-right: 20px;
  background: #f4f5f9;
  border-radius: 8px;
  position: relative;
  border: 1px solid transparent;
  cursor: pointer;
  .check {
    display: none;
  }
  img {
    margin-right: 8px;
  }

  &.on {
    background: #f4f5f9;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #04d1b8;
    .check {
      position: absolute;
      bottom: 6px;
      right: 6px;
      z-index: 11;
      width: 9px;
      height: 9px;
      display: block;
      margin: 0;
    }
    &::before {
      content: '';
      background: #04d1b8;
      width: 24px;
      height: 24px;
      position: absolute;
      border-radius: 35px 0px 8px 0px;
      bottom: 0;
      right: 0;
      z-index: 10;
      overflow: hidden;
    }
  }
}
.addr {
  font-weight: 400;
  font-size: 14px;
  color: #1c1f23;
  margin-bottom: 8px;
}
.head {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}
</style>
